//
// Created by HP on 2025/11/26.
//

#include "Game.h"
#include <iostream>

Game::Game() : Model("games") {
    this->status = "draft";
    setTableDefault("title", "VARCHAR(200) NOT NULL");
    setTableDefault("content", "TEXT NOT NULL");
    setTableDefault("role", "VARCHAR(200) NOT NULL");
    setTableDefault("status", "VARCHAR(50) NOT NULL DEFAULT 'draft'");
    setTableDefault("publicTime", "VARCHAR(200) NOT NULL");
    setTableDefault("createdAt", "DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP");
    setTableDefault("updatedAt", "DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP");
}

void Game::bind(const std::string& key, const std::string& value) {
    if (!TableCols.count(key)) {
        std::cerr << "Error: Invalid key for notification bind" << std::endl;
        return;
    }
    if (TableCols[key].find("UNIQUE") == std::string::npos && key != "id") {
        std::cerr << "Error: Key is not unique for notification bind" << std::endl;
        return;
    }

    std::string selectSql = "SELECT * FROM " + TableName + " WHERE " + key + " = '" + Model::escapeSqlLiteral(value) + "';";
    std::vector<std::map<std::string, std::string>> result = DBConnector::getInstance()->query(selectSql);

    if (result.empty()) {
        std::cerr << "bind failed: SQL execution error or no result. SQL: " << selectSql << std::endl;
        return;
    }

    std::cout << "bind success. Table: " << TableName << std::endl;

    if (result.size() > 1) {
        std::cerr << "Error: Multiple notifications found with the same " << key << std::endl;
        return;
    } else if (result.size() == 1) {
        this->id = result[0]["id"];
        this->title = result[0]["title"];
        this->content = result[0]["content"];
        this->role = result[0]["role"];
        this->status = result[0]["status"];
        this->publicTime = result[0]["publicTime"];
        this->createdAt = result[0]["createdAt"];
        this->updatedAt = result[0]["updatedAt"];
    }
}

bool Game::save() {
    std::string createNotificationSql = "INSERT INTO " + TableName + " (title, content, role,status, publicTime) VALUES ('"
                                        + Model::escapeSqlLiteral(title) + "', '"
                                        + Model::escapeSqlLiteral(content) + "', '"
                                        + Model::escapeSqlLiteral(role) + "', '"
                                        + Model::escapeSqlLiteral(status) + "', '"
                                        + Model::escapeSqlLiteral(publicTime)+ "');";
    int executeCode = DBConnector::getInstance()->execute(createNotificationSql);
    if (executeCode == -1) {
        std::cerr << "create notification failed: SQL execution error. SQL: " << createNotificationSql << std::endl;
        return false;
    } else {
        std::cout << "create notification success. Table: " << TableName << std::endl;
        return true;
    }
}
